<template>
  <page-header-wrapper>
    <a-button type="primary" @click="BackupModal()" style="margin-bottom:10px">数据备份</a-button>
    <a-modal
      title="数据备份"
      :visible="backVisible"
      v-if="backVisible"
      :footer="null"
      @cancel="handleBackupCancel()"
      :maskClosable="false"
    >
      <a-button @click="startBackup({})" :loading="buttonLoading" type="primary" style="margin-bottom:5%">开始备份</a-button>
      <a-form-model :label-col="{span: 6}" :wrapper-col="{span: 18}" id="form">
        <a-form-model-item label="当前正在备份表">
          <span>{{ responseData.nowtable }}</span>
        </a-form-model-item>
        <a-form-model-item label="正在备份表索引">
          <span>{{ responseData.nowtableidx }}</span>
        </a-form-model-item>
        <a-form-model-item label="当前表已备份条数">
          <span>{{ responseData.nowtableexeccount }}</span>
        </a-form-model-item>
        <a-form-model-item label="当前表总条数">
          <span>{{ responseData.nowtabletotal }}</span>
        </a-form-model-item>
        <a-form-model-item label="当前表进度">
          <a-progress :percent="responseData.tablepercentage"></a-progress>
        </a-form-model-item>
        <a-form-model-item label="总进度">
          <a-progress :percent="responseData.totalpercentage"></a-progress>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :rowClassName="rowClassName"
      @change="handleTableChange"
      :pagination="pagination"
      :scroll="{ x: 1200 }"
      :loading="tableLoading"
    >
      <template slot="action" slot-scope="text, record">
        <a @click="handleDownload(record)">下载</a>
        <a-divider type="vertical" />
        <a-popconfirm
          v-if="dataSource.length"
          title="确定操作?"
          okText="确定"
          cancelText="取消"
          @confirm="() => onDisabled(record)"
        >
          <a href="javascript:;" style="color:red">删除</a>
        </a-popconfirm>
        <!-- <a-divider type="vertical" /> -->
        <!-- <a-popconfirm
          v-if="dataSource.length"
          title="确定操作?"
          okText="确定"
          cancelText="取消"
          @confirm="() => onDisabled(record,0)"
        >
          <a href="javascript:;" style="color:red">删除</a>
        </a-popconfirm> -->
      </template>
    </a-table>
  </page-header-wrapper>
</template>

<script>
import { backUp, tableFinds, tableEdit, bacDownload } from '@/api/backUp'
export default {
  data () {
    return {
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '50']
      },
      tableLoading: false,
      buttonLoading: false,
      backVisible: false,
      responseData: {},
      dataSource: [],
      columns: [
        {
          title: '备份名称',
          dataIndex: 'back_name',
          key: 'back_name'
        },
        {
          title: '创建人',
          dataIndex: 'username',
          key: 'username'
        },
        {
          title: '创建时间',
          dataIndex: 'create_time',
          key: 'create_time'
        },
        {
          title: '备份大小',
          dataIndex: 'size',
          key: 'size'
        //   width: '8%'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          key: 'action',
          fixed: 'right'
        }
      ]
    }
  },
  methods: {
    startBackup (data) {
      this.buttonLoading = true
      backUp(data).then(res => {
        this.responseData = res.result
        if (res.result.totalpercentage < 100) {
          this.startBackup(res.result)
        }
        // eslint-disable-next-line eqeqeq
        if (res.result.totalpercentage == 100) {
          // this.startBackup(res.result)
          backUp(res.result).then(res => {
            this.responseData = res.result
            this.buttonLoading = false
            this.$notification['success']({
              message: '备份成功'
            })
            this.getTableData()
            // this.responseData = {}
            this.backVisible = false
          })
        }
      }).catch(err => {
        this.buttonLoading = false
        this.$notification['error']({
          message: err.code,
          description: err.message
        })
      })
    },
    BackupModal () {
      // console.log('???????')
      this.responseData = {}
      this.backVisible = true
    },
    handleBackupCancel () {
      this.responseData = {}
      this.backVisible = false
    },
    rowClassName () {
      return 'rowClass'
    },
    handleTableChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getTableData(this.search)
    },
    getTableData (query) {
      // console.log(query)
      this.tableLoading = true
      var fd = new FormData()
      fd.append('per_page', this.pagination.pageSize)
      fd.append('current_page', this.pagination.current)
      fd.append('type_kinds', this.expertGroup)
      if (query) {
        fd.append('query', query)
      }
    //   console.log(fd)
      tableFinds(fd).then(res => {
        // console.log(res.headers)
        this.dataSource = res.result.data
        Object.assign(this.pagination, { 'pageSize': Number(res.result.per_page), 'total': res.result.total, 'current': res.result.current_page })
        // console.log(this.pagination)
        this.tableLoading = false
      })
      .catch(err => {
        this.$notification['error']({
          message: 'Error',
          description: err.message
        })
      })
    },
    onDisabled (data) {
      var fd = new FormData()
      fd.append('backup_id', data.backup_id)
      tableEdit(fd).then(res => {
        // console.log(res.data)
        if (res.code === 200) {
          this.$notification['success']({
            message: 'Success',
            description: '操作成功'
          })
          this.getTableData()
        } else {
          this.$notification['error']({
            message: 'Error',
            description: res.message
          })
        }
      }).catch(err => {
          this.$notification['error']({
            message: 'Error',
            description: err.message
          })
      })
    },
    handleDownload (record) {
      var fd = new FormData()
      fd.append('backup_id', record.backup_id)
      bacDownload(fd).then(response => {
        // console.log(response.headers)
        const link = document.createElement('a') // 创建下载标签
        const blob = new Blob([response], { type: 'application/zip' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)// 创建url对象
        // link.download = response.headers['content-disposition'].split('=')[1] // 下载后文件名
        // link.download = JSON.parse(sessionStorage.header['content-disposition']).split('=')[1]
        var header = JSON.parse(sessionStorage.header)
        link.download = header['content-disposition'].split('=')[1]
        document.body.appendChild(link)
        link.click()// 开始下载
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)// 销毁url对象
      })
    }
  },
  created () {
    this.getTableData()
  }
}
</script>

<style lang="less" scoped>
#form /deep/ .ant-form-item-label {
  text-align: left;
}
/deep/ .rowClass{
  background-color: #fff;
}
/deep/ .ant-table-thead > tr > th {
  background: #fafafa !important;
}
</style>
